package test;

import java.io.IOException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * SSH客户端脚本执行器
 * 
 * @author 丁明威
 */
public class CommandExcutor {
	final static String DEFAULT_USER = "root";

	final static Logger logger = LoggerFactory.getLogger(CommandExcutor.class);

	public static SSH getSsh(String address, String password) {
		return new SSH(address, DEFAULT_USER, password);
	}

	public static SSH getSsh(String address, String username, String password) {
		return new SSH(address, username, password);
	}

	public static boolean execute(SSH ssh, String command) {
		if (null == ssh) {
			logger.error("SSH client is null");
			return false;
		}
		try {
			if (!ssh.connect()) {
				return false;
			}
		} catch (IOException e1) {
			logger.error("Create SSH connection whith command:[{}] error", command, e1);
			return false;
		}
		try {
			return ssh.execute(command);
		} catch (Exception e) {
			logger.error("Execute command:[{}] error", command, e);
			return false;
		} finally {
			ssh.close();
		}

	}

	public static String execute4Result(SSH ssh, String command) {
		if (null == ssh) {
			logger.error("SSH client is null");
			return null;
		}
		try {
			if (!ssh.connect()) {
				return null;
			}
		} catch (IOException e1) {
			logger.error("Create SSH connection whith command:[{}] error", command, e1);
			return null;
		}
		try {
			return ssh.executeWithResult(command, 60 * 1000);
		} catch (Exception e) {
			logger.error("Execute command:[{}] error", command, e);
			return null;
		} finally {
			ssh.close();
		}
	}

	/**
	 * 带返回结果的执行命令
	 * 
	 * @return BusinessResult
	 * @author sxp
	 * @since V1.0 Feb 9, 2017
	 */
	public static BusinessResult execute4BusinessResult(SSH ssh, String command) {
		if (null == ssh) {
			return new BusinessResult(false, "SSH尚未初始化");
		}

		try {
			if (!ssh.connect()) {
				return new BusinessResult(false, "SSH连接失败");
			}
		} catch (IOException e1) {
			return new BusinessResult(false, "创建SSH连接（命令：[" + command + "]）失败：" + e1.getMessage());
		}

		try {
			return ssh.executeWithBusinessResult(command, 60 * 1000);
		} catch (Exception e) {
			return new BusinessResult(false, "执行命令：[" + command + "]失败：" + e.getMessage());
		} finally {
			ssh.close();
		}
	}

	/**
	 * Test
	 * 
	 * @author sxp
	 */
	public static void main(String[] args) {
		SSH ssh = CommandExcutor.getSsh("192.168.1.138", "root", "password");

		String command = "docker run -p 8080:8080 192.168.1.139:5000/centos-tomcat-helloworld:1.0";
		BusinessResult result = CommandExcutor.execute4BusinessResult(ssh, command);
		System.out.println(result);

	}

}
